/**
 * Created by yanghaibo on 2016/10/25.
 */
ActivityCreateNewMemberSmController = function () {

    // 渲染第一页数据
    this.initFirstPage = function(data) {
        var self = this;
        if(ACTIVITY_TYPE.NEW_MEMBER.val==createActivityPublicParam.activityType){
            data.newMemberShow = true;
        }
        var activityName = Constants.activity.getActivityName(createActivityPublicParam.activityType);
        $("#smCreateNewPage head title").html(activityName);
        $("#smCreateNewPage .header .middle").html(activityName);

         // 渲染模板
        var newData = $.extend(true,{},data);
        newData.voucherWorthValue = parseFloat(newData.voucherWorthValue).toFixed(2);
        CommonUtil.render($("#smCreateNewPage .page-body"), "initActivityNewMemberTPL", newData);
        
        //重新绑定时间控件的事件
        //初始化日期控件;          
        ActivityUtil.loadTimeWidget(true,function(){
            var activityDateParams = createActivityPublicParam.selectDateParams;
            activityDateParams.dateType = "activityDate";
            activityDateParams.pageId = "smCreateNewPage";
            activityDateParams.beginDateInputId = "activityStartTime";
            activityDateParams.endDateInputId = "activityEndTime";
            activityDateParams.selectBeginDateFunc = function(selectTime){
                if(selectTime != createActivityPublicParam.activityStartTime){
                    createActivityPublicParam.activityStartTime = selectTime;
                    //createActivityPublicParam.activityEndTime = DateUtil.getDateFormat(DateUtil.addDays(DateUtil.str2Date(selectTime),30));
                    $("#smCreateNewPage #activityEndTime").val("");
                    ActivityUtil.loadTimeWidget(true);
                    //self.queryExpectEffect(false);
                }
            };
            activityDateParams.selectEndDateFunc = function(selectTime){
                if(selectTime != createActivityPublicParam.activityEndTime){
                    createActivityPublicParam.activityEndTime = selectTime;
                    ActivityUtil.loadTimeWidget(true);

                    if(ACTIVITY_TYPE.NEW_MEMBER.val==createActivityPublicParam.activityType){
                        //获取预期效果数据
                        self.queryExpectEffect(false);
                    }else{
                        self.redrawDefaultView(true);
                    }
                }       
            };
            
        });

    };

    // 渲染券信息
    this.redrawVoucherView = function(data) {
        // 渲染模板
        var newData = $.extend(true,{},data);
        newData.voucherWorthValue = parseFloat(newData.voucherWorthValue).toFixed(2);
        CommonUtil.render($("#smCreateNewPage .quan-area"), "voucherViewTPL", newData);

    };

    // 渲染活动预期效果
    this.redrawExpectEffectView = function(data) {
         // 渲染模板
        CommonUtil.render($("#smCreateNewPage .activity-expect-effect"), "expectEffectTPL", data);
    };

    // 渲染恢复默认按钮
    this.redrawDefaultView = function(flag) {
         // 渲染模板
         var data ={"defaultShow":flag}
        CommonUtil.render($("#smCreateNewPage .btn-wrap"), "defaultViewTPL", data);
    };



    /**
        恢复券信息
    **/
    this.recoverVoucher = function(){
        var defaultParam = createActivityPublicParam.defaultParam;
        var otherSetting = createActivityPublicParam.otherSetting;
        otherSetting.voucherWorthValue = defaultParam.voucherWorthValue;
        otherSetting.voucherMinConsume = defaultParam.voucherMinConsume;
        otherSetting.voucherRelativeTime = defaultParam.voucherRelativeTime;

        createActivityPublicParam.activityStartTime = defaultParam.activityStartTime;
        createActivityPublicParam.activityEndTime = defaultParam.activityEndTime;
    }

    //获取活动预期效果
    this.queryExpectEffect = function(isDefault){
        var self = this;
        if(isDefault){
            var effectData = createActivityPublicParam.defaultParam;
            effectData.isBetter = null;
            self.redrawExpectEffectView(effectData);
        }else{
            var otherSetting = createActivityPublicParam.otherSetting;
            var defaultParam = createActivityPublicParam.defaultParam;
            var diagnoseDate = defaultParam.diagnoseDate;
            var diagnoseCode = defaultParam.diagnoseCode;
            var configCode = encodeURIComponent(defaultParam.configCode);

            var serverUrl = App.serverUrl +　"merchantApp/smartMarketing/queryForecast.do?";
            serverUrl = serverUrl+"isDefault="+isDefault+"&diagnoseDate="+diagnoseDate+"&diagnoseCode="+diagnoseCode;
            if($.isEmptyObject(isDefault)&&!isDefault){

                var activityStartTime = createActivityPublicParam.activityStartTime;
                var activityEndTime = createActivityPublicParam.activityEndTime;
                var voucherWorthValue = otherSetting.voucherWorthValue;
                var voucherMinConsume = otherSetting.voucherMinConsume;
                var voucherRelativeTime = otherSetting.voucherRelativeTime;
                var voucherType =  defaultParam.voucherType;
                var percentageClauseRate =  createActivityPublicParam.percentageClauseRate;
               
                serverUrl = serverUrl
                            +"&configCode="+configCode
                            +"&activityStartTime="+activityStartTime
                            +"&activityEndTime="+activityEndTime
                            +"&voucherWorthValue="+voucherWorthValue
                            +"&voucherMinConsume="+voucherMinConsume
                            +"&voucherRelativeTime="+voucherRelativeTime
                            +"&voucherType="+voucherType
                            +"&percentageClauseRate="+percentageClauseRate
                            ;
            }
            var sucFunc = function (result) {
                if (String(result.success) == 'true') {
                    var effectData = result.resultObject;
                    if(effectData){

                        //处理逻辑,比较与默认的效果数据
                        var old = createActivityPublicParam.defaultParam;
                        if(isDefault){
                            old = effectData;
                        }else{
                            //effectData.isBetter = false;
                            var oldValue = parseFloat(old.tradeAmtRangeMax.replace(',',''));
                            var newValue = parseFloat(effectData.tradeAmtRangeMax.replace(',',''));
                            if(oldValue>newValue){
                                effectData.isBetter = false;
                            }else if(oldValue<newValue){
                                effectData.isBetter = true;
                            }else{
                                effectData.isBetter = null;
                            }
                        }
                        
                        self.redrawExpectEffectView(effectData);
                        return;
                    }

                } else {
                    DialogUtil.dialogWarn(result.msg);
                }
            };

            var failFunc = function () {
                log4JS.info("queryForecast failed. http status not 200");
                DialogUtil.dialogWarn();
            };
            CommonUtil.sendJsonpRequest({"url":serverUrl,"success":sucFunc,"error":failFunc});
            
        }
        
    }


     /**
     * 检查口碑客数据;
     */
    this.checkKbKData = function(){
         
        var percentageClauseRate = $("#smCreateNewPage .percentageClauseRate").val();
        if(percentageClauseRate == ""){
              DialogUtil.dialogWarn("请填写佣金比例!");
              return false;
        }
        if(isNaN(percentageClauseRate)){
             DialogUtil.dialogWarn("分佣比例仅允许输入数字!");
             return false;
        }


        var kbkConfigInfo = createActivityPublicParam.kbkConfigInfo;
        if(percentageClauseRate<kbkConfigInfo.minCommissionPercentage){
            DialogUtil.dialogWarn("分佣比例不能小于"+kbkConfigInfo.minCommissionPercentage+"%");
            return false;
        }
        if(percentageClauseRate>99.99){
            DialogUtil.dialogWarn("分佣比例不能大于99.99%");
            return false;
        }
 
        
        if($("#smCreateNewPage div[name='fenyong-deadline']").find("span").text()=="限制"){
            var percentageClauseMax = $("#smCreateNewPage .percentageClauseMax").val();

            if(percentageClauseMax == ""){
                  DialogUtil.dialogWarn("请填写分佣上限!");
                  return false;
            }
            if(isNaN(percentageClauseMax)){
                DialogUtil.dialogWarn("分佣上限仅允许输入数字!");
                return false;
            }
            if(percentageClauseMax < 0.01 || percentageClauseMax > kbkConfigInfo.maxMaxAmount){
                DialogUtil.dialogWarn("分佣上限仅支持0.01~"+kbkConfigInfo.maxMaxAmount   +"范围内!");
                return false;
            }
 
        }
        
        return true;
        
    }


    /**
     * 保存口碑客
    **/
    this.saveCommissionData = function(){

        var self = this;
        if(!createActivityPublicParam.isOpenKbk){
            var kbk = $("#smCreateNewPage .qudao-item .channel_kbk");
            kbk.removeClass("checked");
            createActivityPublicParam.percentageClauseRate = "";
            createActivityPublicParam.percentageClauseMax ="";
            createActivityPublicParam.commissionSettingCheck = "0";
        }else{
            var percentageClauseRate = $("#smCreateNewPage #qudao-kbk .percentageClauseRate").val();
            createActivityPublicParam.percentageClauseRate = percentageClauseRate;

            var percentageClauseMax = $("#smCreateNewPage #qudao-kbk .percentageClauseMax").val();
            var clauseLimit = $("#smCreateNewPage div[name='fenyong-deadline']").children("span").text();
            if(clauseLimit=="限制"){
                createActivityPublicParam.commissionSettingCheck = "1";
                createActivityPublicParam.percentageClauseMax =percentageClauseMax;
            }else{
                createActivityPublicParam.commissionSettingCheck = "0";         
            }
            $("#smCreateNewPage .qudao-item .channel_kbk").addClass("checked");
        }

        

        if(ACTIVITY_TYPE.NEW_MEMBER.val==createActivityPublicParam.activityType){
            //获取预期效果数据
            self.queryExpectEffect(false);
        }
    }

    /**
     * 初始化佣金页面数据;
     */
    this.initCommissionPageData = function(){
        if(!$("#smCreateNewPage .qudao-item .channel_kbk").hasClass("checked")){
            if(!createActivityPublicParam.isOpenKbk){
                $("#smCreateNewPage label[name='checkSwitch']").find("input").prop("checked",false);

                $("#smCreateNewPage #qudao-kbk .sure").addClass("disabled");
                $("#qudao-kbk .form-wrapper>ul").find("li").each(function(){     
                     if($(this).attr("class")!=null && $(this).attr("class").indexOf("ischange")!=-1){
                         $(this).addClass("disabled");   
                         $(this).find("div").find("input").attr("readonly","readonly");
                     }
                  });
                  $("#smCreateNewPage span[name='kbk_desc']").text("开启口碑客"); 
            }
           //设置口碑客默认值
          $("#smCreateNewPage .percentageClauseRate").val(createActivityPublicParam.defaultParam.defaultCommissionRate);
            $("#smCreateNewPage .switch-label").find("span").text("不限制");
            $("#smCreateNewPage .switch-label").siblings("p").hide(); 

        }
    }

    /**
     * 保存支付宝专享优惠页面数据;
     */
    this.saveZfbData = function(){
        createActivityPublicParam.voucherSlogan =$("#smCreateNewPage .discountDoc").val();//专属优惠文案

        createActivityPublicParam.voucherSloganLocalOldFilePath = createActivityPublicParam.voucherSloganLocalFilePath;//专属优惠图片本地文件path,新路径和老路径进行同步;
        createActivityPublicParam.voucherSloganUri = createActivityPublicParam.voucherSloganNewUri;//保存专享优惠新图片url;
        createActivityPublicParam.voucherSloganUrlId = createActivityPublicParam.voucherSloganNewId;//保存专享优惠新图片id;
    
        //$("#smCreateNewPage .qudao-item .channel_zfb").addClass("checked");
    }


    /**
     * 初始化支付宝专享优惠页面数据;
     */
    this.initZfbPageData = function(){
        $("#smCreateNewPage .discountDoc").val(createActivityPublicParam.voucherSlogan); 
        var picElt = "";
        var voucherSloganPicUrl = createActivityPublicParam.voucherSloganLocalFilePath;
        if(voucherSloganPicUrl!=""){
            picElt = "<img src='"+voucherSloganPicUrl+"' alt='优惠专属图片'/><i class='zhk-list_rarrow'></i>";        
        }else{
            picElt = "非必选项<i class='zhk-list_rarrow'></i>";
        }
        $("#smCreateNewPage .discountPic").find("a").html(picElt);

    }


    /**
     * 检查代金券信息;
     */
    this.checkVoucherData = function(){
        var voucherWorthValue = $("#smCreateNewPage .dailog-form .voucherWorthValue").val();
        var voucherMinConsume = $("#smCreateNewPage .dailog-form .voucherMinConsume").val();
        var voucherRelativeTime = $("#smCreateNewPage .dailog-form .voucherRelativeTime").val();
        
        if (voucherWorthValue == "") {
            DialogUtil.dialogWarn("请您填写券面额!");
            return false;
        }
        if(isNaN(voucherWorthValue)){
            DialogUtil.dialogWarn('券面额仅允许输入数字');
            return false;
        }
        if (voucherWorthValue <= 0 || voucherWorthValue > 999.99) {
            DialogUtil.dialogWarn("券面额必须输入大于0且小于999.99的数字!");
            return false;
        }
        if (voucherMinConsume == "") {
            DialogUtil.dialogWarn("请填写券消费门槛!");
            return false;
        }
        if(isNaN(voucherMinConsume)){
            DialogUtil.dialogWarn('券消费门槛金额仅允许输入数字');
            return false;
        }
 
        if (voucherMinConsume < 0 || voucherMinConsume > 9999.99) {
            DialogUtil.dialogWarn("券消费门槛金额必须输入大于等于0且小于9999.99的数字!");
            return false;
        }

        if (voucherRelativeTime <= 0 || voucherRelativeTime == "") {
            DialogUtil.dialogWarn("券有效期相对时间最小为1天");
            return false;
        }
        if (!(/^\+?(0|[1-9][0-9]*)$/.test(voucherRelativeTime))) {
            DialogUtil.dialogWarn('券有效期相对时间仅允许输入整天数');
            return false;
        }
        if (voucherRelativeTime > 365) {
            DialogUtil.dialogWarn("券有效期相对时间不能大于365天!");
            return false;
        }

        if(parseFloat(voucherWorthValue)<parseFloat(voucherMinConsume)*0.05){
            DialogUtil.dialogWarn("为了吸引更多的顾客到店消费,建议券面额不低于订单价的5%");
            return false;
         }
    
        return true;
    }
    
   
    this.saveVoucherData = function(){
        var self = this;
        var voucherWorthValue = $("#smCreateNewPage .dailog-form .voucherWorthValue").val();
        var voucherMinConsume = $("#smCreateNewPage .dailog-form .voucherMinConsume").val();
        var voucherRelativeTime = $("#smCreateNewPage .dailog-form .voucherRelativeTime").val();
        //更新券信息到otherSetting

        var otherSetting = createActivityPublicParam.otherSetting;
        otherSetting.voucherWorthValue = voucherWorthValue;
        otherSetting.voucherMinConsume = voucherMinConsume;
        otherSetting.voucherRelativeTime = voucherRelativeTime;

        //改变券面额后重新生成券名称
        otherSetting.voucherName = buildVourcherName(voucherWorthValue);
        //重新渲染券页面
        self.redrawVoucherView(otherSetting);
        

        if(ACTIVITY_TYPE.NEW_MEMBER.val==createActivityPublicParam.activityType){
            //获取预期效果数据
            self.queryExpectEffect(false);
        }else{
            self.redrawDefaultView(true);
        }
    }
   
    
};